//图片懒加载
import $bus from '@/utils/eventBus'
//导入防抖函数,规定在高频率触发后多少秒内执行函数
import debounce from './debounce';
import svg from '@/image/loading.svg'
// 调用该函数设置src
let imgs = [];

function setImage(img) {
    //处理图片
    //处理后清空处理过的dom
    let resp = img.dom.getBoundingClientRect();
    let clientHeight = document.documentElement.clientHeight;
    const height = resp.height || 150;
    if (resp.top > clientHeight) {
        img.dom.src = svg;
    } else {
        img.dom.src = img.src;
        imgs = imgs.filter((item) => { return img.dom !== item.dom });
    }
}

function setImages() {
    for (const img of imgs) {
        setImage(img)
    }
}

function handleScroll(dom) {
    setImages();
}
$bus.$on('blogScroll', debounce(handleScroll, 1000));

export default {
    inserted(el, binding, ) {
        let img = { dom: el, src: binding.value, }
        imgs.push(img);
        //立即处理一次
        setImage(img)
    },
    //元素解绑时执行事件,元素消失时
    unbind(el) {
        imgs = imgs.filter((img) => { return img.dom != el })
    },



}